<template>
  <div class="popup">
    <div class="popup-inner">
      <slot />
      <div class="canva"></div>
      <button class="popup-close" @click="togglePopup">Close</button>
    </div>
  </div>
</template>
<script setup>
import * as d3 from "d3";
import { onMounted } from "vue";
const props = defineProps(["togglePopup", "freeman","wkDate"]);
console.log(props.wkDate);

const svgWidth = 600,
  svgHeight = 300;
const rectWidth = 24,
  rectPadding = 2;
const leftMargin = 10,
  topMaggin = 10;
const labelLeftMargin = 20,
  labelTopMagin = 10;
const margin = { left: 130, right: 80, top: 20, bottom: 90 };
const innerWidth = svgWidth - margin.left - margin.right;
const innerHeight = svgHeight - margin.top - margin.bottom;

console.log(innerWidth, innerHeight);

const valideDateObject= function(number8){
       if (number8 == 0) {
          return new Date("2022-01-01");
        } else if (number8 == 99999999) {
          return new Date("9999-01-01");
        } else { 
          return eightNum2Date(number8);
        }
       
}

onMounted(() => {
 
  //console.log("onMounted!!!!!!!!!!!!!!!!!!!!!");
  var obj = [];
  props.freeman.forEach((item) => {
    item.history.forEach((record) => {
      obj.push({
        name: item.name,
        projectName: record.projectName,
        startDate: valideDateObject(record.startDate),
        endDate: valideDateObject(record.endDate),
      });
    });
  });
  
  // draw chart
  //console.log("before render.",obj);
  render(obj);
}); // end of onMounted()

const render = (data) => {

  const canvas = d3.select(".canva");

  const svg = canvas.append("svg");
  svg.attr("width", svgWidth).attr("height", svgHeight);

  
  // 比例尺 domain时实际数据，range是屏幕数据，缩放到range大小
  var xScale = d3
    .scaleTime()
    .domain([
      d3.min(data, (d) => Math.min(d.startDate, d.endDate)),
      d3.max(data, (d) => Math.max(d.startDate, d.endDate)),
    ])
    .range([0, innerWidth]);

  
  var yScale = d3
    .scaleBand()
    .domain(data.map((d) => d.name + "." + d.projectName)) // data.map()返回一个新的数组
    .range([0, innerHeight])
    .padding(0.1); //设置间隔

  
  // 更易维护
  const xValue = (d) => {
    return xScale(d.endDate) - xScale(d.startDate);
  };
  const yValue = (d) => d.name + "." + d.projectName;

  var g = svg
    .append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

  // y坐标轴
  var yAxis = d3.axisLeft(yScale);
  yAxis(g.append("g")); // a.append("g").call(yAxis);//等同于
  //上两句话等价于 g.append("g").call(d3.axisLeft(yScale))

  // x坐标
  const formatTime = d3.timeFormat("%Y-%m-%d");
  g.append("g")
    .call(
      d3.axisBottom(xScale).tickFormat(formatTime).ticks(d3.timeMonth.every(1))
    )
    .attr("transform", `translate(0,${innerHeight})`)
    .attr("class", "axis-x");

  d3.select(".axis-x")
    .selectAll(".tick text")
    .attr("transform", "rotate(45)")
    // .attr('transform',"translate(0,4)" )
    .style("font-size", "12px")
    .style("fill", "grey")
    .attr("text-anchor", "start")
    .style("dominant-baseline", "middle");

  // RECTS
  g.selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("width", function (d, i) {
      
      return xValue(d);
    })
    .attr("height", function (d, i) {
      // return rectWidth;
     
      return yScale.bandwidth();
    })
    .attr("x", function (d, i) {
      return xScale(d.startDate);
    }) // 向右移动
    .attr("y", function (d, i) {
      // 向下移动
      return yScale(yValue(d));
    })
    .attr("fill", "steelblue");
 
  // Line wkDate
    g.append("line")
    .attr("x1",xScale(props.wkDate))
    .attr('y1',0)
    .attr('x2',xScale(props.wkDate) )
    .attr('y2',innerHeight )
    .attr('stroke',"red" )
    .attr('stroke-width',"2px" )
    .attr('stroke-opacity',"0.3" )
    //label for wkDate 
    g.append("circle")
    .attr('cx', xScale(props.wkDate) )
    .attr('cy', innerHeight)
    .attr('r',"2px" )
    .attr('stroke',"red" )
    .attr('fill',"red" )
  g.append("g") 
    .append("text")
    .attr('text', formatDate(props.wkDate))
    .attr('x', xScale(props.wkDate) )
    .attr('y', 10)
    .attr('stroke',"red")



  
  //Label start 。注意应该加个class
  var startG = g.append("g");
  var text2 = startG
    .selectAll("text.start-label")
    .data(data)
    .enter()
    .append("text")
    .text(function (d, i) {
      return formatDate(d.startDate);
    })
    .attr("y", function (d, i) {
      return labelTopMagin + yScale(yValue(d));
    })
    .attr("x", function (d, i) {
      return xScale(d.startDate);
    })
    .attr("stroke", "black")
    .style("font-size", "12px")
    .style("text-anchor", "start") // 将文本水平居中对齐
    .style("dominant-baseline", "middle"); // 将文本垂直居中对齐

  // Label EndDate
  var endG = g.append("g");
  var text3 = endG
    .selectAll("text.end-label")
    .data(data)
    .enter()
    .append("text")
    .text(function (d, i) {
      return formatDate(d.endDate);
    })
    .attr("y", function (d, i) {
      //  return labelTopMagin+ (rectWidth+rectPadding)*i ;
      return labelTopMagin+20 + yScale(yValue(d));
    })
    .attr("x", function (d, i) {
      return xScale(d.endDate);
    })
    .attr("stroke", "black")
    .style("font-size", "12px")
    .style("text-anchor", "start") // 将文本水平居中对齐
    .style("dominant-baseline", "middle"); // 将文本垂直居中对齐

  
}; //end of render()

function minAndMaxOfFreeman(data) {
  const dates = data.reduce((acc, obj) => {
    obj.history.map((item) => {
      acc.push(item.startDate);
      acc.push(item.endDate);
    });
    return acc;
  }, []);

  const maxDate = new Date(Math.max(...dates));
  const minDate = new Date(Math.min(...dates));
  return { min: minDate, max: maxDate };
}

function formatDate(today) {
  // const today = new Date();
  const year = today.getFullYear().toString().substr(2, 2);
  let month = (today.getMonth() + 1).toString();
  if (month.length === 1) {
    month = "0" + month;
  }
  let day = today.getDate().toString();
  if (day.length === 1) {
    day = "0" + day;
  }
  const yyyymmdd = year + "/" + month + "/" + day;
  return yyyymmdd;
}

function eightNum2Date(timeString) {
  timeString = "" + timeString;
  
  //const timeString = '20220322123456'; // 2022年3月22日12点34分56秒
  const year = parseInt(timeString.substr(0, 4));
  const month = parseInt(timeString.substr(4, 2)) - 1; // 月份从0开始计数，所以要减去1
  const day = parseInt(timeString.substr(6, 2));
  // const hour = parseInt(timeString.substr(8, 2));
  // const minute = parseInt(timeString.substr(10, 2));
  // const second = parseInt(timeString.substr(12, 2));

  const date = new Date(year, month, day, 0, 0, 0);
  return date;
}
</script>


<style scoped>
.popup {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
  background: rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid blue;
}

.popup-inner {
  background: white;
  /* position: relative; */
  padding: 32px;
  border: 1px solid black;
}
</style>